package com.fasteat.common.util;

import org.springframework.util.StringUtils;

import java.util.HashMap;
import java.util.Map;


/**
 * @author ghost
 * @description 驼峰转化工具类
 * @since 2021-1-27
 */
public class CamelUtil {

	/**
	 * 下划线转成驼峰
	 */
	public static String underlineToCamel(String param) {
		if (StringUtils.isEmpty(param)) {
			return "";
		}
		int len = param.length();
		StringBuilder sb = new StringBuilder(len);
		for (int i = 0; i < len; i++) {
			char c = param.charAt(i);
			if (c == '_') {
				if (++i < len) {
					sb.append(Character.toUpperCase(param.charAt(i)));
				}
			} else {
				sb.append(c);
			}
		}
		return sb.toString();
	}


	/**
	 * 驼峰法转下划线
	 */
	public static String camelToUnderline(String s) {
		if (StringUtils.isEmpty(s)) {
			return "";
		}
		StringBuilder sb = new StringBuilder();
		boolean upperCase = false;
		for (int i = 0; i < s.length(); i++) {
			char c = s.charAt(i);
			boolean nextUpperCase = true;
			if (i < (s.length() - 1)) {
				nextUpperCase = Character.isUpperCase(s.charAt(i + 1));
			}
			if ((i >= 0) && Character.isUpperCase(c)) {
				if (!upperCase || !nextUpperCase) {
					if (i > 0) sb.append('_');
				}
				upperCase = true;
			} else {
				upperCase = false;
			}
			sb.append(Character.toLowerCase(c));
		}
		return sb.toString();
	}

	/**
	 * 将map中的key下划线转成驼峰
	 */
	public static Map<String, Object> formatMapWithCamel(Map<String, Object> map) {
		if (map == null || map.size() <= 0) {
			return null;
		}
		HashMap<String, Object> ret = new HashMap<>(map.size() + 1);
		map.keySet().forEach((key) -> {
			ret.put(underlineToCamel(key), map.get(key));
		});
		return ret;
	}

	/**
	 * 将map中的key驼峰转成下划线
	 */
	public static Map<String, String> formatMapWithUnderline(Map<String, String> map) {
		if (map == null || map.size() <= 0) {
			return null;
		}
		HashMap<String, String> ret = new HashMap<>(map.size() + 1);
		map.keySet().forEach((key) -> {
			ret.put(camelToUnderline(key), map.get(key));
		});
		return ret;
	}

}
